import { Feature } from "ol";
import { createFeature } from "../create/createFeature";
import { createPointGeometry } from "../create/createGeometry";
import { createHeatmapLayer as heatmapLayer } from "../create/createLayer";
import { createSource } from "../create/createSource";
import { transform4326to3857 } from "../utils/transform";
import { Coordinate } from "ol/coordinate";
import { Heatmap } from "ol/layer";

export interface CreateHeatmapOptions {
  getLngKey?: string;
  getLatKey?: string;
  getValueKey?: string;
  style?: ConstructorParameters<typeof Heatmap>[0];
}

export function createHeatmapLayer<T>(
  data: T[],
  options?: CreateHeatmapOptions
) {
  const features: Feature[] = [];
  const {
    getLngKey = "lng",
    getLatKey = "lat",
    getValueKey = "value",
    style = {},
  } = options || {};
  const points: Coordinate[] = [];
  data.forEach((item) => {
    const lng = item[getLngKey as keyof T];
    const lat = item[getLatKey as keyof T];
    if (lng !== undefined && lat !== undefined) {
      const coordinate = transform4326to3857([lng as number, lat as number]);

      const feature = createFeature(createPointGeometry(coordinate));
      feature.set("data", item);
      features.push(feature);
    }
  });

  const source = createSource();
  source.addFeatures(features);

  const layer = heatmapLayer({
    source,
    blur: 20, // 模糊尺寸
    radius: 20, // 热点半径
    opacity: 0.8,
    weight: getValueKey, /* (feature) => {
      const data = feature.get("data") as T;
      const count = Number(data[getValueKey as keyof T]); // 获取feature的weight参数值
      const magnitude = count / 1;
      return magnitude;
    } */
    ...style,
  });
  return layer;
}
